﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.Models;
using MvcMusicStore.ViewModels;


namespace MvcMusicStore.Controllers
{
    public class ShoppingCartController : Controller
    {
        MusicStoreEntities db = new MusicStoreEntities();
        // GET: /ShoppingCart/

        public ActionResult Index()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);
            var viewModel = new ShoppingCartViewModel { 
            CartItems=cart.GetCartItems(),
            CartTotal=cart.GetTotal()
            };

            return View(viewModel);
        }
        public ActionResult AddToCart(int id)
        {
            var additem = db.Albums.Single(c=>c.AlbumId==id);
            var cart = ShoppingCart.GetCart(this.HttpContext);
            cart.AddCart(additem);
            return RedirectToAction("Index");        
        }
        [ChildActionOnly]
        public ActionResult CartSummary()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);
            ViewData["CartCount"] = cart.GetCount();
            return PartialView("CartSummary");
        }
        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {

            var cart = ShoppingCart.GetCart(this.HttpContext);
            string albumname = db.Carts.Single(c => c.RecordId == id).Album.Title;
            int itemCount = cart.RemoveFromCart(id);
            var results = new ShoppingCartRemoveViewModel { 
            Message=Server.HtmlEncode(albumname)+"has been remove from your cart!",
            CartTotal=cart.GetTotal(),
            CartCount=cart.GetCount(),
            ItemCount=itemCount,
            DeleteId=id
            
            };
            return Json(results);
        }

    }
}
